﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Text;
using DAL;

namespace PeisongWeb.admin
{
    public partial class weeklyOrderEdit : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                drpCompanyBind();
            }
        }

        /// <summary>
        /// 绑定所有采购商
        /// </summary>
        private void drpCompanyBind()
        {
            DataSet ds = logic.company.select("type='2' and ischeck=1 and enabledWeeklyPrice=1", "companyid", 1000, 1);

            drp_company.DataSource = ds.Tables[1];
            drp_company.DataBind();
            drp_company.Items.Insert(0, new System.Web.UI.WebControls.ListItem("--请选择--", ""));

            ext_receiveDt.SelectedDate = DateTime.Now.AddDays(1);

            ddl_receiveTime.DataSource = logic.sysCode.receiveTime();
            ddl_receiveTime.DataBind();
            //ddl_receiveTime.Items.Insert(0, new System.Web.UI.WebControls.ListItem("--请选择送货时间--", ""));
        }

        // 弹出选择商品窗口
        protected void lbn_AddProduct_Click(object sender, EventArgs e)
        {
            rptProBind();
            win_product.Show();
        }

        protected void drp_company_SelectedIndexChanged(object sender, EventArgs e)
        {
            rpt_pro.DataBind();
            hd_proScope.Value = "";
            if (drp_company.SelectedValue.Trim() != "")
            {
                DataSet ds = logic.company.select("companyid=" + drp_company.SelectedValue.Trim(), "companyid", 1, 1);
                DataRow dr = ds.Tables[1].Rows[0];
                lbl_contact.Text = dr["contact"].ToString();
                lbl_Address.Text = dr["area"].ToString() + dr["address"].ToString();
                lbl_contactMobile.Text = dr["mobile"].ToString();
                lbl_contactPhone.Text = dr["Phone"].ToString();
            }
            else
            {
                lbl_contact.Text = "请选择公司";
                lbl_Address.Text = "请选择公司";
                lbl_contactMobile.Text = "请选择公司";
                lbl_contactPhone.Text = "";
            }
        }

        protected void lbn_search_Click(object sender, EventArgs e)
        {
            rptProBind();
        }

        /// <summary>
        /// 绑定在采购商的周价商品
        /// </summary>
        void rptProBind()
        {
            int companyId = Convert.ToInt32(drp_company.SelectedValue);
            int week = (int)Math.Round(((double)DateTime.Now.DayOfYear / 7));
            DataTable dt=logic.buyerWeeklyPrice.buyerWeeklyProductList(companyId,week);
            rpt_Products.DataSource = dt;
            rpt_Products.DataBind();
        }

        protected void AspNetPager2_PageChanged(object sender, EventArgs e)
        {
            rptProBind();
        }

        // 生成订单数据
        protected void btn_Save_Click(object sender, EventArgs e)
        {
            int companyid = Convert.ToInt32(drp_company.SelectedValue);
            OrderEntity od = new OrderEntity();
            od.Amount = Convert.ToDecimal(hd_TotalAmount.Value);    //支付总价
            od.CompanyId = companyid;                               //采购商ID
            od.StandardAmount = od.Amount;                          //汇总总价
            od.CustomerId = logic.sysAdmin.AdminID;                 //用户ID，电话订单就代表录入者ID
            od.FireightFee = Convert.ToDecimal(txt_fireightFee.Value);  //运费
            od.Note = txt_Note.Text;                                     //备注
            od.OrderNo = ""; //传空值，存储过程自动得到订单编号
            od.Source = "2";    //订单来源：1、网站订单；2、电话订单
            od.Taxfee = Convert.ToDecimal(txt_taxfee.Value); //税费
            od.Status = "1";  //订单状态：“1”：已提交；“2”备货中；“3”已发货；“4”交易成功；“5”交易关闭；
            //string time = ddl_receiveTime.SelectedValue.Substring(ddl_receiveTime.SelectedValue.IndexOf("-") + 1, ddl_receiveTime.SelectedValue.Length - (ddl_receiveTime.SelectedValue.IndexOf("-") + 1));
            //od.ReceiveDt = Convert.ToDateTime(ext_receiveDt.Value).AddHours(Convert.ToInt32(time.Substring(0,time.IndexOf(":"))));    //收货时间

            string timeRange = ddl_receiveTime.SelectedItem.Text;
            int hour = Convert.ToInt32(timeRange.Substring(timeRange.IndexOf("-") + 1, timeRange.Length - (timeRange.IndexOf("-") + 4)));
            od.ReceiveDt = Convert.ToDateTime(ext_receiveDt.Value).AddHours(hour);    //收货时间

            string[] splitstr = { "," };
            string[] str_vpros = hd_proScope.Value.Split(splitstr, StringSplitOptions.RemoveEmptyEntries);
            od.TypeCount = str_vpros.Length / 5;
            int orderid = logic.order.insert(od);
            for (int i = 0; i < str_vpros.Length; i += 5)
            {
                int proid = Convert.ToInt32(str_vpros[i]);  //商品ID
                OrderItemEntity _oritem = new OrderItemEntity();
                _oritem.CustomerId = logic.sysAdmin.AdminID;
                _oritem.ProductId = proid;
                _oritem.Price = Convert.ToDecimal(str_vpros[i + 2]);  //商品价格
                _oritem.Quantity = Convert.ToDecimal(str_vpros[i + 3]); //数量
                _oritem.InitQuantity = Convert.ToDecimal(str_vpros[i + 3]); //实际数量
                _oritem.Note = str_vpros[i + 4] == "0" ? "" : str_vpros[i + 4];     //备注
                _oritem.OrderId = orderid;
                PriceEntity pr = logic.price.getByProduct(proid,companyid);
                _oritem.SellerId = pr.CompanyId;                //供应商ID
                _oritem.SellerPrice = pr.SellerPrice;           //供应价格
                _oritem.Unit = pr.Unit;                         //单位
                logic.orderItem.insert(_oritem);
            }
            Library.Script.ClientMsgUrl("订单保存成功!", "orderList.aspx");
        }

        /// <summary>
        /// 选择要添加到订单中的商品
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void lbn_AddOrderItem_Click(object sender, EventArgs e)
        {
            for (int i = 0; i < rpt_Products.Items.Count; i++)      //循环Repeater
            {
                RepeaterItem row = rpt_Products.Items[i];
                HiddenField hidproId = row.FindControl("hid_productId") as HiddenField;
                Label lblproName = row.FindControl("lbl_proName") as Label;
                Label lblprice = row.FindControl("lbl_price") as Label;
                TextBox txtQuantity = row.FindControl("txtQuantity") as TextBox;
                TextBox txtnote = row.FindControl("txtNote") as TextBox;
                CheckBox cbxSelect = row.FindControl("cbx_isSelect") as CheckBox;
                if (cbxSelect.Checked)            //找到选择的商品加入数据库
                {
                    int proid = Convert.ToInt32(hidproId.Value);
                    String proName = lblproName.Text;
                    Decimal price = Convert.ToDecimal(lblprice.Text);
                    Decimal count = Convert.ToDecimal(txtQuantity.Text);
                    String note = txtnote.Text == "" ? "0" : txtnote.Text;
                    String strs = hd_proScope.Value;
                    String newValue = "";
                    String[] pArray = strs.Split(',');
                    newValue = proid + "," + proName + "," + price + "," + count + "," + note + ",";
                    //判断是该商品编号是否存在于最近访问的记录里面
                    for (int j = 0; j < pArray.Length - 1; j += 5)
                    {
                        if (pArray[j] != proid.ToString())
                        {
                            newValue += pArray[j] + "," + pArray[j + 1] + "," + pArray[j + 2] + "," + pArray[j + 3] + "," + pArray[j + 4] + ",";
                        }
                    }
                    hd_proScope.Value = newValue;
                }
            }

            bindSelectPros();
        }

        void bindSelectPros()
        {
            String strs = hd_proScope.Value;
            String[] pros = strs.Split(',');
            Decimal total = 0;
            DataTable dt = new DataTable();
            dt.Columns.Add("number", Type.GetType("System.Int32"));
            dt.Columns.Add("proName", System.Type.GetType("System.String"));
            dt.Columns.Add("price", System.Type.GetType("System.Decimal"));
            dt.Columns.Add("quantity", System.Type.GetType("System.Decimal"));
            dt.Columns.Add("note", System.Type.GetType("System.String"));
            dt.Columns.Add("proId", System.Type.GetType("System.Int32"));
            dt.Columns.Add("amount", System.Type.GetType("System.Decimal"));
            for (int i = 0; i < pros.Length - 1; i += 5)
            {
                DataRow dr = dt.NewRow();
                dr[0] = (i / 5 + 1);
                dr[1] = pros[i + 1];
                dr[2] = pros[i + 2];
                dr[3] = pros[i + 3];
                dr[4] = pros[i + 4] == "0" ? "" : pros[i + 4];
                dr[5] = pros[i];
                dr[6] = Convert.ToDecimal(string.Format("{0:F2}", Convert.ToDecimal(pros[i + 2]) * Convert.ToDecimal(pros[i + 3])));
                total += Convert.ToDecimal(string.Format("{0:F2}", Convert.ToDecimal(pros[i + 2]) * Convert.ToDecimal(pros[i + 3])));
                dt.Rows.Add(dr);
            }

            rpt_pro.DataSource = dt;
            rpt_pro.DataBind();
            span_proSum.InnerHtml = hd_TotalAmount.Value = total.ToString();
            //加上税费、运费
            Decimal taxfee = Convert.ToDecimal(txt_taxfee.Value);
            Decimal fireightFee = Convert.ToDecimal(txt_fireightFee.Value);
            txt_Amount.Value = lbl_StandardAmount.Text = String.Format("{0:F2}", total + taxfee + fireightFee);
        }

        //删除商品
        protected void rpt_pro_ItemCommand(object source, RepeaterCommandEventArgs e)
        {
            if (e.CommandName == "DEL")
            {
                int proid = Convert.ToInt32(e.CommandArgument);
                String strs = hd_proScope.Value;
                String newValue = "";
                String[] pArray = strs.Split(',');
                //判断是该商品编号是否存在于最近访问的记录里面
                for (var i = 0; i < pArray.Length - 1; i += 5)
                {
                    if (Convert.ToInt32(pArray[i]) != proid)
                    {
                        newValue += pArray[i] + "," + pArray[i + 1] + "," + pArray[i + 2] + "," + pArray[i + 3] + "," + pArray[i + 4] + ",";
                    }
                }
                hd_proScope.Value = newValue;

                bindSelectPros();
            }
        }
    }
}
